package com.example.teaching_server.controller;

import com.example.teaching_server.common.ApiResponse;
import com.example.teaching_server.dto.MenuDTO;
import com.example.teaching_server.dto.ResourceRequestDTO;
import com.example.teaching_server.entity.TeachingResource;
import com.example.teaching_server.entity.TeachingResourceType;
import com.example.teaching_server.service.TeachingResourceService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/api/teaching-resources")
@RequiredArgsConstructor
@Tag(name = "教学资源管理", description = "教学资源查询和管理接口")
public class TeachingResourceController {

    private final TeachingResourceService teachingResourceService;

    /**
     * 获取左侧菜单
     */
    @GetMapping("/menu")
    @Operation(summary = "获取左侧菜单", description = "获取教学资源左侧菜单列表")
    public ApiResponse<List<MenuDTO>> getLeftMenu() {
        log.info("开始获取教学资源左侧菜单");

        try {
            List<MenuDTO> menu = teachingResourceService.getLeftMenu();
            log.info("成功获取{}个菜单项", menu.size());
            return ApiResponse.success("菜单获取成功", menu);
        } catch (Exception e) {
            log.error("获取菜单失败", e);
            return ApiResponse.fail("菜单获取失败: " + e.getMessage());
        }
    }

    /**
     * 获取所有资源类型
     */
    @GetMapping("/types")
    @Operation(summary = "获取资源类型", description = "获取所有可用的教学资源类型")
    public ApiResponse<List<TeachingResourceType>> getResourceTypes() {
        log.info("开始获取教学资源类型");

        try {
            List<TeachingResourceType> types = teachingResourceService.getAllResourceTypes();
            log.info("成功获取{}个资源类型", types.size());
            return ApiResponse.success("资源类型获取成功", types);
        } catch (Exception e) {
            log.error("获取资源类型失败", e);
            return ApiResponse.fail("资源类型获取失败: " + e.getMessage());
        }
    }

    /**
     * 根据条件获取资源
     */
    @PostMapping("/list")
    @Operation(summary = "获取资源列表", description = "根据子类别ID、类型ID和关键字查询教学资源")
    public ApiResponse<List<TeachingResource>> getResources(@RequestBody ResourceRequestDTO request) {
        log.info("开始查询教学资源: subcategoryId={}, typeId={}, keyword={}",
                request.getSubcategoryId(), request.getTypeId(), request.getKeyword());

        try {
            List<TeachingResource> resources = teachingResourceService.getResourcesByCriteria(
                    request.getSubcategoryId(), request.getTypeId(), request.getKeyword()
            );
            log.info("成功查询到{}个教学资源", resources.size());
            return ApiResponse.success("资源获取成功", resources);
        } catch (Exception e) {
            log.error("获取资源失败", e);
            return ApiResponse.fail("资源获取失败: " + e.getMessage());
        }
    }
}
